﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApp.拦截器
{
    /// <summary>
    /// 订单拦截输入 工厂
    /// 定义数据来源
    /// </summary>
    public class OrderInterceptInputFactory
    {
        public OrderInterceptInputFactory()
        {
        }

        public IEnumerable<OrderInterceptInput> GetList(IEnumerable<OrderMain> orders)
        {
            if (orders == null)
            {
                return Enumerable.Empty<OrderInterceptInput>();
            }
            var orderArray = orders.ToArray();

            var lazyOrderDetails = new Lazy<OrderDetail[]>(() => GetOrderDetails(orderArray).ToArray(), true);
            var lazyProducts = new Lazy<Product[]>(()=>GetProducts(lazyOrderDetails.Value).ToArray(),true);

            return orderArray.Select(x => new OrderInterceptInput(x,
                lazyOrderDetails,
                lazyProducts
                ));
        }

        /// <summary>
        /// 设置订单详情数据源
        /// </summary>
        /// <param name="orders"></param>
        /// <returns></returns>
        private IEnumerable<OrderDetail> GetOrderDetails(OrderMain[] orders)
        {
            if (orders == null || !orders.Any()) return Enumerable.Empty<OrderDetail>();

            var orderCodes = orders.Select(x => x.OrderCode).ToArray();
            return DBData.GetOrderDetailsDBData().Where(x => orderCodes.Contains(x.OrderCode)).ToArray();
        }

        /// <summary>
        /// 设置产品数据源
        /// </summary>
        /// <param name="orderDetails"></param>
        /// <returns></returns>
        private IEnumerable<Product> GetProducts(OrderDetail[] orderDetails)
        {
            if (orderDetails == null || !orderDetails.Any())
                return Enumerable.Empty<Product>();
            var skus = orderDetails.Select(x => x.SKU).ToArray();
            return DBData.GetProductsDBData().Where(x => skus.Contains(x.SKU)).ToArray();
        }


    }
}
